#!/usr/bin/env python

import sys
import string
import irccmds
import re
import optparse
import time

SERVER = "irc.freenode.net"
PORT = 6667
NICK = "GBOT"
#IDENT = NICK
#REALNAME = NICK
CHANNEL = "#jaybocc2"
MSGLEN = 8
OWNER = "jaybendon"
COUNT = 1
REGISTER = False

#sets the irccmd module and the class irccmds() to the variable irc
irc = irccmds.irccmds()
#sets the irccmd module and the class ircparse() to the variable ircparse
ircparse = irccmds.ircparse()

#parses command line parameters on startup.
def parseopt():
  global SERVER
  global NICK
  global CHANNEL
  global OWNER
  global PASS
  global REGPASS
  global REGEMAIL
  global REGISTER
  global REGISTERED
  parseopt = optparse.OptionParser()
  parseopt = optparse.OptionParser(usage="%prog [OPTIONS]")
  parseopt.add_option( "-s", "--server", dest="server", help="ip or hostname of the irc server to connect to" )
  parseopt.add_option( "-n", "--nick", dest="nick", help="nickname to be used by the bot" )
  parseopt.add_option( "-c", "--channel", dest="channel", help="#channel for the bot to join" )
  parseopt.add_option( "-o", "--owner", dest="owner", help="owners nickname" )
  parseopt.add_option( "-p", "--pass", action="store_true", dest="password", default=True, help="sets password on script run" )
  parseopt.add_option( "-r", "--register", action="store_true", dest="register", default=False, help="tells the bot to register with the irc server" )
  parseopt.add_option( "-R", "--registered", action="store_true", dest="registered", default=False, help="tells the bot it is registered with the irc server" )

  (options, args) = parseopt.parse_args()

  if options.server:
    SERVER = options.server

  if options.nick:
    NICK = options.nick

  if options.channel:
    CHANNEL = options.channel

  if options.owner:
    OWNER = options.owner

  if options.password == True:
    PASS = raw_input('Please specify an admin password: ')

  if options.register == True:
    print 'registering'
    REGISTER = True
    REGPASS = raw_input('Please specify a password to register with the nickserv: ')
    REGEMAIL = raw_input('Please specify an email to register with the nickserv: ')

  if options.registered == True:
    print 'registered'
    REGISTERED = True
    REGPASS = raw_input('Please specify a password to register with the nickserv: ')
    REGEMAIL = raw_input('Please specify an email to register with the nickserv: ')

#connects to the irc server and sets the nickname, user identity and joins a channel
def opencon(server, port, nick, channel, owner):
  irc.connect(server, port)
#  irc.passw('thisisnotarealpassword')
  irc.nick(nick)
#  irc.user(nick, server, nick)
  if REGISTER == True:
    irc.privmsg('nickserv', "REGISTER %s %s\r\n" % (REGPASS, REGEMAIL))
    time.sleep(10)
  time.sleep(10)
  if REGISTERED == True:
    irc.privmsg('nickserv', "REGISTER %s %s\r\n" % (REGPASS, REGEMAIL))
  time.sleep(10)
  irc.user(nick, server, nick)
#  irc.join(channel)

def parseping(a):
  """parseping(line) will parse line for PING and respond with the appropriate
  PONG"""
  for line in a:
    print line
    line = string.rstrip(line)
    line = string.split(line)

    if  (line[0] == "PING"):
      irc.pong(line[1])

def botcommands(cmd, usr, line):
  """botcommands(cmd, usr, line) will parse the cmd, usr and line parameters and
  execute the appropriate command"""
  if cmd == "QUIT":
    if usr == OWNER and PASS == ircparse.getpwd(line):
      irc.privmsg(CHANNEL, "%s is my owner. I will quit now\r\n" % usr)
      irc.quit("Quitting because %s told me to.\r\n" % usr)
      global COUNT
      COUNT = 0
      sys.exit("Exiting because owner issued QUIT command.")
    else:
      irc.privmsg(ircparse.getusr(line), "You are not my owner.  Command denied.\r\n")
  elif cmd == "OPME":
    irc.op(ircparse.getchan(line), usr)
  else:
    irc.privmsg(CHANNEL, "Invalid command.\r\n")

#main loop that the ircbot runs on
def mainloop():
  readbuffer = ''
  COUNT = 1
  chanjoined = False
  while COUNT == 1:
    readbuffer = readbuffer + irc.socks.myreceive()
    temp = string.split(readbuffer, "\n")
    readbuffer = temp.pop( )

    parseping(temp)
    if chanjoined == False:
      irc.join(CHANNEL)
      chanjoined = True

    for line in temp:

      if ircparse.getbotcall(line) == NICK:
        botcommands(ircparse.getcmd(line), ircparse.getusr(line), line)

      if ircparse.getirccmd(line) == "JOIN":
        irc.op(ircparse.getchanjoin(line), ircparse.getusr(line))
  sys.exit("Exiting...")

if __name__ == "__main__":
  parseopt()
  opencon(SERVER, PORT, NICK, CHANNEL, OWNER)
  mainloop()
